329B - Biridian Forest - CodeForces Solution


dfs and similar shortest paths *1500

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;
 
const int N = 1024;
const int INF = INT_MAX;
 
char a[N][N];
int dp[N][N];
 
const pair<int, int> dist[4] = {
	{0, 1}, {1, 0}, {0, -1}, {-1, 0}
};
 
void matrix_init(int a, int b) {
	for (int i = 0; i <= a + 1; ++i)
		for (int j = 0; j <= b + 1; ++j)
			if (dp[i][j] != -INF)
				dp[i][j] = INF;
 
	for (int i = 0; i <= b + 1; ++i)
		dp[0][i] = dp[a + 1][i] = -INF;
 
	for (int i = 0; i <= a + 1; ++i)
		dp[i][0] = dp[i][b + 1] = -INF;
}
 
void bfs(pair<int, int> v) {
	dp[v.first][v.second] = 0;
	
	queue<pair<int,int>> q;
	q.push({ v.first, v.second });
	
	while (!q.empty()) {
		pair<int, int> cur = q.front();
		q.pop();
 
		for (int i = 0; i < 4; ++i) {
			int x = cur.first + dist[i].first;
			int y = cur.second + dist[i].second;
			int val = dp[cur.first][cur.second];
 
			if (dp[x][y] > -INF)
				if (dp[x][y] > val + 1) {
					dp[x][y] = val + 1;
					q.push({ x, y });
				}
		}
	}
}
 
signed main() {
	int n, m;
	cin >> n >> m;
 
	pair<int, int> start, exit;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j) {
			cin >> a[i][j];
			if (a[i][j] == 'S')
				start = { i, j };
			
			if (a[i][j] == 'E')
				exit = { i, j };
			
			if (a[i][j] == 'T')
				dp[i][j] = -INF;
		}
	
	matrix_init(n, m);
	bfs(exit);
 
	int ans = 0;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			if (dp[i][j] <= dp[start.first][start.second])
				ans += (a[i][j] - '0') * (a[i][j] >= '0' && a[i][j] <= '9');
	
	cout << ans << '\n';
}/*1698131912.8649504*/


Comments

Submit
0 Comments
More Questions

1302. Deepest Leaves Sum
1209. Remove All Adjacent Duplicates in String II
994. Rotting Oranges
983. Minimum Cost For Tickets
973. K Closest Points to Origin
969. Pancake Sorting
967. Numbers With Same Consecutive Differences
957. Prison Cells After N Days
946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST